<template>
  <div>
    <el-card class="top"><el-header>添加红包</el-header></el-card>

    <!-- 表格展示 -->
    <el-card>
      <el-input placeholder="红包名称" prefix-icon="el-icon-search" style="width: 200px" v-model="name">
      </el-input>
      <el-button type="warning" @click="reload" plain>查询</el-button>
      <el-button type="warning" @click="addformVisible = true">新增红包</el-button>
      <el-table :data="goodsList" style="width: 100%" :sort-by.sync="sortKey"
        :sort-orders="['ascending', 'descending']">
        <el-table-column type="index" label="编号" width="60" align="center">
        </el-table-column>
        <el-table-column prop="name" label="红包名称" width="150" align="center">
        </el-table-column>
        <el-table-column prop="money" label="红包金额(元)" width="140" align="center" sortable>
        </el-table-column>
        <el-table-column prop="num" label="总数" width="100" align="center" sortable>
        </el-table-column>
        <el-table-column prop="starttime" label="开始时间" width="200" align="center" sortable>
        </el-table-column>
        <el-table-column prop="endtime" label="结束时间" width="200" align="center" sortable>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="150" align="center" sortable>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="scope">
            <!-- v-if="canEditAndDelete"  v-else-->
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="stop(scope.row)">停止</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增 -->
    <el-dialog title="新增红包信息" :visible.sync="addformVisible" :modal-append-to-body="false">
      <el-form :model="addform">
        <el-form-item label="红包名称" :label-width="formLabelWidth">
          <el-input v-model="addform.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="红包金额" :label-width="formLabelWidth">
          <el-input v-model="addform.money" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="红包个数" :label-width="formLabelWidth">
          <el-input v-model="addform.num" autocomplete="off"></el-input>
        </el-form-item>
        <el-date-picker label="时间范围" v-model="timevalue" type="datetimerange" range-separator="至"
          start-placeholder="开始时间" end-placeholder="结束时间" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
          @change="changeTime">
        </el-date-picker>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addformVisible = false">取 消</el-button>
        <el-button type="primary" @click="add()">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑 -->
    <el-dialog title="修改红包信息" :visible.sync="editformVisible" :modal-append-to-body="false">
      <el-form :model="editform">
        <el-form-item label="红包名称" :label-width="formLabelWidth">
          <el-input v-model="editform.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="红包金额" :label-width="formLabelWidth">
          <el-input v-model="editform.money" autocomplete="off">
          </el-input>
        </el-form-item>
        <el-form-item label="红包总数" :label-width="formLabelWidth">
          <el-input v-model="editform.num" autocomplete="off">
          </el-input>
        </el-form-item>
        <el-date-picker label="时间范围" v-model="editform.timevalue" type="datetimerange" range-separator="至"
          start-placeholder="开始时间" end-placeholder="结束时间" size="mini" value-format="yyyy-MM-dd HH:mm:ss"
          @change="changeTime">
        </el-date-picker>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editformVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit()">确 定</el-button>
      </div>
    </el-dialog>

    <!--    分页-->
    <el-row>
      <el-col style="text-align:right">
        <el-pagination :current-page="currentPage" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :page-size="pageSize" :page-sizes="[5, 10, 15]" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>

</template>

<script>
import { del } from 'vue';

export default {
  data() {
    return {
      state: "",
      user: {},
      name: "",
      goodsList: [],
      addformVisible: false,
      editformVisible: false,
      buyformVisible: false,
      timevalue: [new Date(), new Date()],
      addform: {
        uid: null,
        name: null,
        money: null,
        num: null,
        starttime: null,
        endtime: null,
      },
      editform: {
        name: '',
        money: '',
        num: '',
        starttime: null,
        endtime: null,
        timevalue: []
      },
      formLabelWidth: '120px',
      //配置分页
      currentPage: 1,
      pageSize: 5,
      total: 0,
      sortKey: ''
    };
  },

  computed: {
    // 根据用户角色决定是否显示编辑和删除按钮
    canEditAndDelete() {
      return this.userRole === 'admin';
    }
  },

  mounted() {
    this.reload();
    if (localStorage.getItem("user")) {
      this.user = JSON.parse(localStorage.getItem("user"))
      console.log("111111111111" + JSON.stringify(this.user.uid));

    }
  },


  methods: {
    //添加
    add() {
      console.log(this.addform);
      this.addform.uid = this.user.uid
      this.$axios.post("/killredEnvelope/addkill", this.addform).then(res => {
        console.log(res);
        if (res.data.code == 200) {
          //对话框消失
          this.addformVisible = false;
          //清空新增留存上一个数据
          this.addform = {};
          //给出添加成功或者失败提示
          this.$message({
            message: "添加成功",
            type: 'success'
          });
          this.reload();
        } else {
          this.addformVisible = false
          this.$message({
            message: "添加失败",
            type: 'error'
          });
        }
      })
    },

    // 编辑
    edit() {

      if (this.state == "已结束" || this.state == "进行中") {
        this.$message({
          message: "无法编辑",
          type: 'error'
        });
        this.editformVisible = false
      } else {
        this.editform.starttime = this.editform.timevalue[0];
        this.editform.endtime = this.editform.timevalue[1];
        console.log(this.editform);
        this.$axios.put("/killredEnvelope/editKillRedEnvelope", this.editform).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: "编辑成功",
              type: 'success'
            });
            this.editformVisible = false
            this.reload();
          } else {
            this.$message.console.error("编辑失败");
          }
        })
      }
    },

    watch: {
      editformVisible(val) {
        if (val) {
          // 当编辑表单显示时，将starttime和endtime转换为timevalue
          this.editform.timevalue = [this.editform.starttime, this.editform.endtime];
        }
      }
    },

    // 停止
    stop(row) {
      console.log(row);
      if (row.state == "已结束" || row.state == "进行中") {
        this.$message({
          message: "无法停止",
          type: 'error'
        });
      } else {
        this.$axios.put("/killredEnvelope/stopKillFromRedis/" + row.id).then(res => {
          if (res.data.code == 200) {
            this.$message({
              message: "停止成功",
              type: 'success'
            });
            this.reload();
          } else {
            this.$message.console.error("停止失败");
          }
        })
      }
    },

    reload() {
      this.$axios.get("/killredEnvelope/findAll?currentPage=" + this.currentPage + "&pageSize=" + this.pageSize + "&name=" + this.name).then((res) => {
        console.log(res.data.data);
        this.goodsList = res.data.data.list;
        this.total = res.data.data.total;
        this.money = res.data.data.list.money;
        console.log(res.data.data.money);
      });
    },

    handleEdit(row) {
      this.editformVisible = true;
      this.editform = { ...row };
      console.log(this.editform.state);
      this.state = this.editform.state

    },

    handleBuy(row) {
      this.buyform = { ...row };
    },

    handleChange(value) {
      console.log(value);
    },

    //显示查询出的总条数
    handleSizeChange(val) {
      this.pageSize = val;
      this.reload();
    },

    //点击新页查询的数据
    handleCurrentChange(val) {
      this.currentPage = val;
      this.reload();
    },

    changeTime() {
      this.addform.starttime = this.timevalue[0]
      this.addform.endtime = this.timevalue[1]

      this.editform.starttime = this.timevalue[0]
      this.editform.endtime = this.timevalue[1]
    }
  },
};
</script>

<style scoped>
.el-header {
  text-align: center;
  line-height: 30px;
  size: 120px;
}

.top {
  background-color: #D3D3D3;
  height: 60px;
}

.el-card {
  margin-top: 10px;
  margin-left: 30px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>